// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()
const db = cloud.database();
// 云函数入口函数
exports.main = async (event, context) => new Promise((resolve, reject) => {
    console.log(event)
    const wxContext = cloud.getWXContext()
    const missionId = event.missionId;
    const data = { ...event };
    delete data.userInfo;
    delete data.missionId;
    if(!missionId) reject('缺少missionId')
    console.log(data)
    db.collection('mission').doc(missionId).update({
        data
    }).then(res => {
        let description;
        if (data.hasOwnProperty('star')) {
            description = data.star?'星标了任务':'取消了星标'
        } else if (data.hasOwnProperty('status')) {
            description ='将任务状态修改为'
            switch (data.status) {
                case 'done':
                    description += '【完成】';
                    break;
                case 'doing':
                    description += '【进行中】';
                    break;
                case 'delay':
                    description += '【推迟】';
                    break;
                default:
                    description += '【'+status+'】'
            }
        }
        cloud.callFunction({
            name: 'logMission',
            data: {
                userId: wxContext.OPENID,
                missionId: event.missionId,
                description
            }
        }).then(()=>{
            resolve(res)
        })
    }
    ).catch(err => reject(err))
})